package com.uetoken.cn.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.uetoken.cn.MainActivity;
import com.uetoken.cn.R;
import com.uetoken.cn.base.BaseActivity;
import com.uetoken.cn.bean.LoginBean;
import com.uetoken.cn.bean.MsgBean;
import com.uetoken.cn.bean.SignBean;
import com.uetoken.cn.common.ApiHelper;
import com.uetoken.cn.common.Constant;
import com.uetoken.cn.network.OkHttpUtils;
import com.uetoken.cn.network.Params;
import com.uetoken.cn.network.WebResponse;
import com.uetoken.cn.utils.CountDownTimerUtils;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * author : hejunming
 * e-mail : 925379434@qq.com
 * date   : 2018/10/25 11:33
 */
public class BindAndLoginActivity extends BaseActivity implements WebResponse {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.edt_activity_input_new_phone)
    EditText edtActivityInputNewPhone;
    @BindView(R.id.tv_activity_input_new_phone_get_verification_code)
    TextView tvActivityInputNewPhoneGetVerificationCode;
    @BindView(R.id.edt_activity_input_new_phone_please_input_verification_code)
    EditText edtActivityInputNewPhonePleaseInputVerificationCode;
    @BindView(R.id.tv_activity_input_new_phone_confirm_modify)
    TextView tvActivityInputNewPhoneConfirmModify;
    /**
     * 发送短信请求的网络请求码
     */
    public static final int REQUEST_NETWORK_SMS = 10;
    /**
     * 请求登录接口的请求码
     */
    private static final int REQUEST_NETWORK_LOGIN = 20;
    /**
     * 请求签到接口的请求码
     */
    private static final int REQUEST_NETWORK_SIGN = 30;
    /**
     * 请求签到接口的请求码
     */
    private static final int REQUEST_NETWORK_BIND_ID = 40;

    /**
     * 经度
     */
    private String longitude = "0";
    /**
     * 纬度
     */
    private String latitude = "0";
    private String phone;
    private String pwd;
    private String uid;
    private String nodeid;
    private int opentype;
    private CountDownTimerUtils countDownTimerUtils;

    @Override
    public int getLayoutId() {
        return R.layout.activity_input_new_phone;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        //状态栏沉浸式
        BarUtils.setStatusBarColor(this, ContextCompat.getColor(this, android.R.color.white), true);
        BarUtils.setStatusBarLightMode(this, true);
        ivBack.setVisibility(View.VISIBLE);
        tvTitle.setText(R.string.str_bind_ue_account);
        edtActivityInputNewPhone.setHint(getResources().getString(R.string.str_enter_phone_number));
        tvActivityInputNewPhoneConfirmModify.setText(R.string.str_bind_ue_and_login);
    }

    @Override
    public void initData() {
        longitude = getIntent().getStringExtra("longitude");
        latitude = getIntent().getStringExtra("latitude");
        uid = getIntent().getStringExtra("uid");
        opentype = getIntent().getIntExtra("opentype", 0);
    }

    @Override
    public void init() {

    }

    @Override
    public void onSuccessResponse(Call call, String response, int requestCode) throws IOException {
        LogUtils.dTag("BindAndLoginActivity==", "BindAndLoginActivity== requestCode = " + requestCode + " response = " + response);
        switch (requestCode) {
            case REQUEST_NETWORK_SMS:
                break;
            case REQUEST_NETWORK_LOGIN:
                LoginBean loginBean = new Gson().fromJson(response, LoginBean.class);
                if (loginBean.getResult() > 0) {
                    nodeid = String.valueOf(loginBean.getData().getNodeid());
                    //保存用户nodeId
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_NODE_ID, nodeid);
                    //保存用户nodeCode
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_NODE_CODE, loginBean.getData().getNodecode());
                    //保存用户nodeName
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_NODE_NAME, loginBean.getData().getNodename());
                    //保存用户手机号
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_MOBILE_NO, loginBean.getData().getMobileno());
                    //保存用户头像地址
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_HEAD_PHOTO, loginBean.getData().getPic());
                    //保存值为true，代表用户已登录
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_WHETHER_LOGIN, true);
                    //保存是否有支付密码的状态
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.IS_PAY_PWD, loginBean.getData().isIspaypwdnull());
                    //保存最大免密支付金额
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_MAXIMUM_SECRET_AMOUNT, String.valueOf(loginBean.getData().getMaxnotpwd()));
                    bindThirdpartyID();
                } else {
                    dissmissDialog();
                }
                ToastUtils.showShort(loginBean.getMessage());
                break;
            case REQUEST_NETWORK_BIND_ID:
                dissmissDialog();
                MsgBean msgBean = new Gson().fromJson(response, MsgBean.class);
                if (msgBean.getResult() > 0) {
                    beginSign();
                    ActivityUtils.finishActivity(MainActivity.class);
                    startActivity(new Intent(this, MainActivity.class));
                    finish();
                }
                ToastUtils.showShort(msgBean.getMessage());
                break;
            case REQUEST_NETWORK_SIGN:
                //签到接口返回的result=-1时，为冻结状态
                SignBean signBean = new Gson().fromJson(response, SignBean.class);
                if (signBean.getResult() <= 0) {
                    ToastUtils.showShort(signBean.getMessage());
                    if (signBean.getResult() == -1) {
                        SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_WHETHER_LOGIN, false);
                    }
                }
                break;
        }
    }

    @Override
    public void onFailResponse(Call call, IOException e, int requestCode) {
        dissmissDialog();
        ToastUtils.showShort(e.getMessage());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimerUtils != null) {
            countDownTimerUtils.cancel();
        }
    }

    /**
     * 登录
     */
    private void Login() {
        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(BindAndLoginActivity.this, ApiHelper.getLoginUrl(), REQUEST_NETWORK_LOGIN,
                Params.getLoginParams(phone, pwd, ""));
    }

    /**
     * 开始签到
     */
    private void beginSign() {
        OkHttpUtils.getInstance().getStringWithParam(BindAndLoginActivity.this, ApiHelper.getUserSignUrl(), REQUEST_NETWORK_SIGN,
                Params.getUserSignParams(longitude, latitude));
    }

    /**
     * 绑定第三方账号接口
     */
    private void bindThirdpartyID() {
        OkHttpUtils.getInstance().getStringWithParam(BindAndLoginActivity.this, ApiHelper.getBindThirdpartyUrl(), REQUEST_NETWORK_BIND_ID,
                Params.getBindThirdpartyParams(nodeid, opentype + "", uid));
    }

    /**
     * 获取验证码
     */
    private void getAuthCode() {
        phone = edtActivityInputNewPhone.getText().toString();
        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showShort(getResources().getString(R.string.str_phone_not_be_empty));
            return;
        }
        if (!RegexUtils.isMobileSimple(phone)) {
            ToastUtils.showShort(getResources().getString(R.string.str_phone_not_specification));
            return;
        }
        countDownTimerUtils = new CountDownTimerUtils(this, tvActivityInputNewPhoneGetVerificationCode, 60000, 1000);
        countDownTimerUtils.start();
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getSendSMSUrl(), REQUEST_NETWORK_SMS, Params.getSmsParams(phone));
    }

    @OnClick({R.id.iv_back, R.id.tv_activity_input_new_phone_get_verification_code, R.id.tv_activity_input_new_phone_confirm_modify})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_activity_input_new_phone_get_verification_code:
                getAuthCode();
                break;
            case R.id.tv_activity_input_new_phone_confirm_modify:
                phone = edtActivityInputNewPhone.getText() + "";
                pwd = edtActivityInputNewPhonePleaseInputVerificationCode.getText() + "";
                Login();
                break;
        }
    }
}

